<template>
  <el-card style="max-width: 2000px">
    <template #header>
      <div class="card-header">
        <div class="query">
          <!-- 筛选条件 -->
          <el-select
            v-model="selectedYear"
            placeholder="请选择年份"
            style="width: 120px"
            clearable
          >
            <el-option
              v-for="year in years"
              :key="year"
              :label="year"
              :value="year"
            />
          </el-select>

          <el-select
            v-model="selectedQuestionType"
            placeholder="请选择题型"
            style="width: 180px"
            clearable
          >
            <el-option
              v-for="type in questionTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>

          <el-input
            v-model="queryStr"
            style="width: 240px"
            placeholder="搜索题目内容"
          />&nbsp;
          <el-button
            class="button"
            type="primary"
            round
            @click="queryInfo"
          >
            搜索
          </el-button>
        </div>
      </div>
    </template>

    <el-table
      :data="currentTableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" :selectable="selectable" width="55" />
      <el-table-column prop="question_id" label="编号" width="150" />
      <el-table-column prop="year" label="年份" width="150" />
      <el-table-column label="题型" width="150">
        <template #default="scope">
        {{ getQuestionTypeLabel(scope.row.question_type) }}
        </template>
      </el-table-column>
      <el-table-column prop="content" label="题目内容" width="900" />
      <el-table-column fixed="right" label="操作" min-width="180">
        <template #default="scope">
          <el-link
            type="info"
            :underline="false"
            @click="showDetail(scope.row)"
          >
            详情
          </el-link>
          
          <el-link
            type="primary"
            :underline="false"
            style="margin: 0 10px"
            @click="openUpdateDialog(scope.row)"
          >
            编辑
          </el-link>
          
          <el-popconfirm
            title="确定要删除此题目吗?"
            @confirm="singleDelete(scope.row.question_id)"
          >
            <template #content>
              <span>删除后将无法恢复此题目信息</span>
            </template>
            <template #reference>
              <el-link
                type="danger"
                :underline="false"
              >
                删除
              </el-link>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.length"
        prev-text="上一页"
        next-text="下一页"
        page-sizes-text="每页显示条数"
        total-text="共 {total} 条"
        jumper-text="前往"
        size-change-text="条/页"
      >
      </el-pagination>
    </div>
    
    <!-- 编辑弹窗 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="title"
      width="800px"
    >
      <el-form :model="form" label-width="120px" :rules="rules" ref="formRef">
        <el-form-item label="年份" prop="year">
          <el-input
            v-model="form.year"
            type="number"
            placeholder="请输入年份（如：2023）"
          />
        </el-form-item>

        <el-form-item label="题型" prop="question_type">
          <el-select
            v-model="form.question_type"
            placeholder="请选择题型"
          >
            <el-option
              v-for="type in questionTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="题目内容" prop="content">
          <el-input
            type="textarea"
            v-model="form.content"
            :rows="3"
            placeholder="请输入题目内容"
          />
        </el-form-item>

        <!-- 选择题选项，仅在题型为选择题时显示 -->
        <template v-if="form.question_type === 'single_choice'">
          <el-form-item
            v-for="(option, index) in form.options"
            :key="index"
            :label="'选项' + String.fromCharCode(65 + index)"
            :prop="'options.' + index"
            :rules="[
              { required: true, message: '选项内容不能为空', trigger: 'blur' }
            ]"
          >
            <div style="display: flex; align-items: center; gap: 10px;">
              <el-input
                v-model="form.options[index]"
                placeholder="请输入选项内容"
              />
              <el-button
                type="danger"
                circle
                icon="Delete"
                @click="removeOption(index)"
                v-if="form.options.length > 2"
              />
            </div>
          </el-form-item>
          
          <el-form-item>
            <el-button
              type="primary"
              plain
              @click="addOption"
              :disabled="form.options.length >= 6"
            >
              添加选项
            </el-button>
          </el-form-item>
        </template>
      
        <el-form-item label="参考答案" prop="answer">
          <template v-if="form.question_type === 'single_choice'">
            <el-select
              v-model="form.answer"
              placeholder="请选择正确答案"
            >
              <el-option
                v-for="(_, index) in form.options"
                :key="index"
                :label="String.fromCharCode(65 + index)"
                :value="String.fromCharCode(65 + index)"
              />
            </el-select>
          </template>
          <template v-else>
            <el-input
              type="textarea"
              v-model="form.answer"
              :rows="2"
              placeholder="请输入参考答案"
            />
          </template>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">
          {{ btnName }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="题目详情"
      width="800px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="年份">
          {{ currentDetail.year }}
        </el-descriptions-item>
        
        <el-descriptions-item label="题型">
          {{ getQuestionTypeLabel(currentDetail.question_type) }}
        </el-descriptions-item>
        
        <el-descriptions-item label="题目内容">
          <div style="white-space: pre-wrap;">{{ currentDetail.content }}</div>
        </el-descriptions-item>

        <!-- 选择题选项 -->
        <template v-if="currentDetail.question_type === 'single_choice'">
          <el-descriptions-item 
            v-for="(option, index) in currentDetail.options" 
            :key="index"
            :label="`选项${String.fromCharCode(65 + index)}`"
          >
            <div :class="{ 'correct-answer': currentDetail.answer === String.fromCharCode(65 + index) }">
              {{ option }}
            </div>
          </el-descriptions-item>
        </template>

        <el-descriptions-item label="参考答案">
          <div style="white-space: pre-wrap;" class="correct-answer">
            {{ currentDetail.question_type === 'single_choice' ? 
              `选项${currentDetail.answer}` : currentDetail.answer }}
          </div>
        </el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script>
import { ElMessage } from 'element-plus'

export default {
  data() {
    return {
      dialogFormVisible: false,
      detailDialogVisible: false,
      currentDetail: {},
      queryStr: '',
      originalData: [],
      tableData: [],
      multipleSelection: [],
      form: {
        year: '',
        question_type: 'single_choice',
        content: '',
        options: ['', ''], // 默认两个选项
        answer: ''
      },
      title: '',
      btnName: '',
      isEdit: false,
      selectedYear: '',
      selectedQuestionType: '',
      years: ['2020', '2021', '2022', '2023', '2024', '2025'], // 年份选项
       questionTypes: [
      { value: 'single_choice', label: '选择题' }, // value对应数据库英文，label对应显示中文
      { value: 'fill_in_the_blank', label: '填空题' },
      {value: 'calculation', label: '大题' }
    ],
      currentPage: 1,
      pageSize: 10,
      rules: {
        year: [
          { required: true, message: '请输入年份', trigger: 'blur' },
          { 
            validator: (rule, value, callback) => {
              if (value === '') {
                callback(new Error('请输入年份'));
              } else {
                const num = Number(value);
                if (isNaN(num)) {
                  callback(new Error('年份必须为数字'));
                } else if (num < 2000 || num > 2100) {
                  callback(new Error('年份必须在2000-2100之间'));
                } else {
                  callback();
                }
              }
            },
            trigger: 'blur'
          }
        ],
        question_type: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入题目内容', trigger: 'blur' },
          { min: 5, message: '题目内容至少需要5个字符', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请输入参考答案', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    currentTableData() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = this.currentPage * this.pageSize
      return this.tableData.slice(start, end)
    }
  },
  methods: {
    // 加载数据
    async loadData() {
      try {
        const response = await fetch('/api/question/list');
        const data = await response.json();
        
        // 处理每条数据
        this.tableData = data.map(item => {
          // 统一字段名转换
          const normalizedItem = {
            ...item,
            // 统一字段名（处理驼峰和下划线两种格式）
            question_id: item.question_id || item.questionId || item.id,
            question_type: item.question_type || item.questionType || 'unknown',
            year: item.year || '未设置年份',
            content: item.content || '无内容',
            answer: item.answer || ''
          };

          // 处理选项数据
          if (normalizedItem.question_type === 'single_choice' && item.options) {
            try {
              // 如果选项是字符串，尝试解析JSON
              if (typeof item.options === 'string') {
                normalizedItem.options = JSON.parse(item.options);
              } else {
                normalizedItem.options = item.options;
              }
            } catch (error) {
              console.error('解析选项数据失败:', error);
              normalizedItem.options = [];
            }
          }

          return normalizedItem;
        });
        
        this.originalData = [...this.tableData];
        
        // 调试：打印处理后的数据
        if (this.debugMode) {
          console.log("处理后的数据:", this.tableData);
          if (this.tableData.length > 0) {
            console.log("第一条数据:", this.tableData[0]);
            console.log("题型字段:", this.tableData[0].question_type);
          }
        }
      } catch (error) {
        console.error('加载数据失败:', error);
        ElMessage.error('加载数据失败: ' + error.message);
      }
    },

    // 打开编辑弹窗
    openUpdateDialog(row) {
      this.title = '编辑题目'
      this.btnName = '更新'
      this.isEdit = true
      
      // 深拷贝数据，避免直接修改原数据
      const formData = JSON.parse(JSON.stringify(row));
      
      // 处理选项数据
      if (formData.question_type === 'single_choice' && formData.options) {
        try {
          // 如果选项是字符串，尝试解析JSON
          let optionsArray = formData.options;
          if (typeof optionsArray === 'string') {
            optionsArray = JSON.parse(optionsArray);
          }
          
          // 将选项对象数组转换为普通数组
          if (Array.isArray(optionsArray)) {
            formData.options = optionsArray.map(opt => {
              if (typeof opt === 'object') {
                const key = Object.keys(opt)[0];
                return opt[key];
              }
              return opt;
            });
          }
        } catch (error) {
          console.error('解析选项数据失败:', error);
          formData.options = ['', '']; // 如果解析失败，设置默认选项
        }
      } else {
        formData.options = ['', '']; // 非选择题或无选项时，设置默认选项
      }
      
      this.form = formData;
      this.dialogFormVisible = true;
    },
    
    // 提交表单（更新）
    async submitForm() {
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          try {
            // 构造请求数据
            const requestData = {
              year: Number(this.form.year),
              questionType: this.form.question_type,
              content: this.form.content
            };

            // 编辑模式需要添加 questionId
            if (this.isEdit && this.form.question_id) {
              requestData.questionId = this.form.question_id;
            }

            // 处理选项和答案
            if (this.form.question_type === 'single_choice') {
              // 处理选择题选项 - 转换为[{A: "选项1"}, {B: "选项2"}...]格式
              const optionsArray = this.form.options.map((option, index) => ({
                [String.fromCharCode(65 + index)]: option
              }));
              // 将选项数组转换为JSON字符串
              requestData.options = JSON.stringify(optionsArray);
              
              // 选择题答案就是选中的选项字母（A、B、C...）
              requestData.answer = this.form.answer;
            } 
            else if (this.form.question_type === 'calculation') { // 新增大题逻辑
                   requestData.options = '[]'; // 大题无选项
                requestData.answer = this.form.answer; // 直接保存文本答案
                }else {
              // 填空题不需要选项
              requestData.options = '[]';
              // 填空题答案就是文本内容
              requestData.answer = this.form.answer;
            }

            // 发送请求
            const response = await fetch('/api/questions/edit', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify(requestData)
            });

            const result = await response.json();

            if (response.ok) {
              ElMessage.success('更新成功');
              this.dialogFormVisible = false;
              // 只重新加载数据，保持筛选条件和页码不变
              await this.loadData();
              // 重新应用筛选条件
              this.queryInfo();
            } else {
              throw new Error(result.message || '操作失败');
            }
          } catch (error) {
            console.error('提交失败:', error);
            ElMessage.error(error.message || '提交失败，请检查网络连接或服务器状态');
          }
        } else {
          ElMessage.error('表单验证失败，请检查必填项');
          return false;
        }
      });
    },
    
    // 单条删除
    async singleDelete(questionId) {
      try {
        const response = await fetch(`/api/questions/${questionId}`, {
          method: 'DELETE'
        });

        if (response.ok) {
          ElMessage.success('删除成功');
          await this.loadData();
          this.queryInfo();
        } else {
          const result = await response.json();
          throw new Error(result.message || '删除失败');
        }
      } catch (error) {
        console.error('删除失败:', error);
        ElMessage.error(error.message || '删除失败，请检查网络连接或服务器状态');
      }
    },
    
    // 筛选查询
    queryInfo() {
      try {
        const filter = {
          year: this.selectedYear ? this.selectedYear.trim() : '',
          question_type: this.selectedQuestionType ? this.selectedQuestionType.trim() : '',
          content: this.queryStr ? this.queryStr.trim().toLowerCase() : ''
        };

        this.tableData = this.originalData.filter(item => {
          // 年份比较：转换为字符串后比较
          const yearMatch = !filter.year || String(item.year).trim() === filter.year;
          
          // 题型比较：转换为小写后比较
          const typeMatch = !filter.question_type || 
            String(item.question_type).trim().toLowerCase() === filter.question_type.toLowerCase();
          
          // 内容比较：转换为小写，包含即可
          const contentMatch = !filter.content || 
            String(item.content).toLowerCase().includes(filter.content);

          return yearMatch && typeMatch && contentMatch;
        });

        // 重置到第一页
        this.currentPage = 1;

        // 添加搜索结果提示
        if (this.tableData.length === 0) {
          ElMessage.info('未找到匹配的题目');
        }
      } catch (error) {
        console.error('搜索出错:', error);
        ElMessage.error('搜索过程中发生错误');
        this.tableData = [...this.originalData]; // 发生错误时恢复原始数据
      }
    },
    
    // 获取题型中文标签
    getQuestionTypeLabel(type) {
      if (!type) {
        console.warn('题型值为空', type);
        return '未设置题型';
      }
      
      // 统一转换为小写
      const normalizedType = String(type).toLowerCase().trim();
      
      // 查找匹配的题型
      const typeMap = {
        'single_choice': '选择题',
        'singlechoice': '选择题',
        'choice': '选择题',
        'fill_in_the_blank': '填空题',
        'fillintheblank': '填空题',
        'blank': '填空题',
        'essay': '大题',
        'subjective':'主观题',
        'unknown': '未知题型'
      };
      
      // 优先使用预定义映射
      if (typeMap[normalizedType]) {
        return typeMap[normalizedType];
      }
      
      // 尝试在questionTypes中查找
      const matchedType = this.questionTypes.find(
        t => t.value.toLowerCase() === normalizedType
      );
      
      return matchedType ? matchedType.label : `未知题型 (${type})`;
    },
    
    // 添加选项
    addOption() {
      if (this.form.options.length < 6) {
        this.form.options.push('')
      }
    },

    // 删除选项
    removeOption(index) {
      if (this.form.options.length > 2) {
        this.form.options.splice(index, 1)
        // 如果删除的是当前选中的答案，清空答案
        if (this.form.answer === String.fromCharCode(65 + index)) {
          this.form.answer = ''
        }
      }
    },
    
    // 处理多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    
    // 分页大小变化
    handleSizeChange(newSize) {
      this.pageSize = newSize
    },
    
    // 当前页变化
    handleCurrentChange(newPage) {
      this.currentPage = newPage
    },

    // 显示题目详情
    showDetail(row) {
      // 深拷贝数据，避免修改原数据
      this.currentDetail = JSON.parse(JSON.stringify(row));
      
      // 如果是选择题，处理选项数据
      if (this.currentDetail.question_type === 'single_choice' && this.currentDetail.options) {
        try {
          // 如果选项是字符串，尝试解析JSON
          if (typeof this.currentDetail.options === 'string') {
            this.currentDetail.options = JSON.parse(this.currentDetail.options);
          }
          
          // 将选项对象数组转换为普通数组
          if (Array.isArray(this.currentDetail.options)) {
            this.currentDetail.options = this.currentDetail.options.map(opt => {
              if (typeof opt === 'object') {
                const key = Object.keys(opt)[0];
                return opt[key];
              }
              return opt;
            });
          }
        } catch (error) {
          console.error('解析选项数据失败:', error);
          this.currentDetail.options = [];
        }
      }
      
      this.detailDialogVisible = true;
    }
  },
  mounted() {
    this.loadData()
  }
}
</script>

<style>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
}

.query {
  display: flex;
  gap: 15px;
  align-items: center;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.correct-answer {
  color: #67C23A;
  font-weight: bold;
}

.el-descriptions {
  padding: 20px;
}

.el-descriptions__label {
  width: 120px;
}

.center-form-dialog .el-dialog__body {
  display: flex;
  justify-content: center;
}

.center-form {
  width: 80%;
  max-width: 600px;
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 美化卡片 */
.custom-card {
  margin: 20px auto;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

/* 美化详情弹窗 */
.detail-descriptions {
  background-color: #fafafa;
  border-radius: 8px;
}

/* 美化按钮 */
.button {
  transition: all 0.3s ease;
}

.button:hover {
  transform: translateY(-2px);
}

/* 美化输入框 */
.el-input {
  transition: all 0.3s ease;
}

.el-input:hover {
  box-shadow: 0 0 0 2px rgba(45, 140, 240, 0.1);
}

/* 美化表格 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background-color: #f5f7fa;
}
</style>  